package com.tim.app.ui.activity.found;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.roundimg.RoundedImageView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Discover;
import com.tim.app.server.entry.Story;
import com.tim.app.server.result.EveryDayHearListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.MainActivity;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.adapter.found.StoryAdapter;
import com.tim.app.ui.view.EveryDayHeadDetialHeadView;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;

import jp.wasabeef.glide.transformations.BlurTransformation;


/**
 * 每日一听详情页
 */
public class EveryDayHearDetailActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "EveryDayHearDetailActivity";

    private AppBarLayout appbar;
    private ImageView ivBack, ivReport;
    private TextView tvTitle;
    private View vLine;

    private TextView tvDesc;
    private ImageView ivBg;
    private RoundedImageView rivImage;
    private TextView tvEveryDayHearName;

    private boolean isFromPush = false;

    private NestedScrollView isvNsvStory;
    private WrapRecyclerView wrvStory;
    private StoryAdapter adapter;
    private ArrayList<Story> dataList;

    private EveryDayHeadDetialHeadView headView;

    private EveryDayHearListResult.Res.Data data;

    private EmptyLayout emptyLayout;

    public static void start(Context context, boolean isFromPush) {
        Intent intent = new Intent(context, EveryDayHearDetailActivity.class);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_everyday_hear_detail;
    }


    @Override
    public void initView() {
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        ivBack = (ImageView) findViewById(R.id.ivBack);
        ivReport = (ImageView) findViewById(R.id.ivReport);
        tvTitle = (TextView) findViewById(R.id.tvTitle);

        tvDesc = (TextView) findViewById(R.id.tvDesc);
        ivBg = (ImageView) findViewById(R.id.ivBg);

        rivImage = (RoundedImageView) findViewById(R.id.rivImage);
        tvEveryDayHearName = (TextView) findViewById(R.id.tvEveryDayHearName);
        vLine = findViewById(R.id.vLine);

        ivBack.setOnClickListener(this);
        ivReport.setOnClickListener(this);
        rivImage.setOnClickListener(this);

        data = (EveryDayHearListResult.Res.Data) getIntent().getSerializableExtra("everydayHear");
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);

        isvNsvStory = (NestedScrollView) findViewById(R.id.isvNsvStory);
        wrvStory = (WrapRecyclerView) findViewById(R.id.wrvStory);
        wrvStory.setOverScrollMode(View.OVER_SCROLL_NEVER);

        emptyLayout = new EmptyLayout(this, isvNsvStory);
        emptyLayout.showLoading();

        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        wrvStory.setLayoutManager(layoutManager);

        wrvStory.setHasFixedSize(true);
        wrvStory.setNestedScrollingEnabled(false);
        adapter = new StoryAdapter(this, dataList);

        headView = (EveryDayHeadDetialHeadView) LayoutInflater.from(this).inflate(R.layout.everyday_hear_detail_head_view, null);
        wrvStory.addHeaderView(headView);

        adapter.setOnItemClickListener(this);
        wrvStory.setAdapter(adapter);

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset == 0) {  //展开状态
                    ivBack.setImageResource(R.drawable.ic_back_white);
                    ivReport.setImageResource(R.drawable.ic_more_white);
                    tvTitle.setVisibility(View.GONE);
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    vLine.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                    ivReport.setImageResource(R.drawable.ic_more);
                    tvTitle.setVisibility(View.VISIBLE);
                } else {//中间状态
                    vLine.setVisibility(View.GONE);
                    tvTitle.setVisibility(View.GONE);
                }

                int maxScroll = appBarLayout.getTotalScrollRange();
                float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll;
                if (percentage > 0.7f) {
                    tvTitle.setVisibility(View.VISIBLE);
                    ivBack.setImageResource(R.drawable.ic_back_black);
                } else {
                    tvTitle.setVisibility(View.GONE);
                    ivBack.setImageResource(R.drawable.ic_back_white);
                }
            }
        });
        EventManager.ins().registListener(EventTag.DO_PLAY_ALL_AND_INTO, eventListener);
        EventManager.ins().registListener(EventTag.GET_CURRENT_PLAY, eventListener);
        EventManager.ins().registListener(EventTag.ON_PLAY, eventListener);
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_PLAY_ALL_AND_INTO:
                    StoryDetailActivity.start(EveryDayHearDetailActivity.this, dataList, 0, false);
                    break;
                case EventTag.GET_CURRENT_PLAY:
                    int index = arg1;
                    int stated = arg2;
                    ArrayList<Story> storyList = (ArrayList<Story>) dataobj;
                    if (storyList.size() == 0) {
                        return;
                    }
                    Story story = storyList.get(index);
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(story.getId())) {
                            if (stated == 1) {
                                adapter.setIndex(i);
                                adapter.notifyDataSetChanged();
                            }
                            break;
                        }
                    }
                    break;
                case EventTag.ON_PLAY:
                    EventManager.ins().sendEvent(EventTag.ON_GET_CURRENT_PLAY, 0, 0, null);
                    break;
            }
        }
    };


    @Override
    public void initData() {
        API_Discover.ins().getEveryDayHearList(TAG, refreshCallback);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null == dataList || position > dataList.size() - 1)
            return;
        StoryDetailActivity.start(this, dataList, position, false);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                EveryDayHearListResult result = new Gson().fromJson(resultValue, EveryDayHearListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getEverymusic() && null != result.getRes().getEverymusic().getStoryList()) {
                    if (null != result.getRes().getEverymusic().getStoryList()) {
                        dataList.addAll(result.getRes().getEverymusic().getStoryList());
                        adapter.notifyDataSetChanged();
                        data = result.getRes().getEverymusic();
                        refreshUi(data);
                        EventManager.ins().sendEvent(EventTag.ON_GET_CURRENT_PLAY, 0, 0, null);
                        emptyLayout.showContent();
                    } else {
                        emptyLayout.showEmpty();
                    }
                } else {
                    emptyLayout.showEmpty();
                }

            } else {
                emptyLayout.showError();
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };


    private void refreshUi(EveryDayHearListResult.Res.Data data) {
        if (null != data) {
            if (!TextUtils.isEmpty(data.getTitle())) {
                tvDesc.setText(data.getTitle());
                tvTitle.setText(data.getTitle());
            }
            if (!TextUtils.isEmpty(data.getName())) {
                tvEveryDayHearName.setText(data.getName());
            }
            headView.setData(data);
            Glide.with(this)
                    .load(data.getImage()).error(new ColorDrawable(Color.parseColor("#eeeeee"))).into(rivImage);
            Glide.with(this)
                    .load(data.getImage()).error(new ColorDrawable(Color.parseColor("#eeeeee")))
                    .bitmapTransform(new BlurTransformation(this, AppKey.DETIAL_RADIUS))//高斯模糊
                    .into(ivBg);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventManager.ins().sendEvent(EventTag.ON_GET_CURRENT_PLAY, 0, 0, null);
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.DO_PLAY_ALL_AND_INTO, eventListener);
        EventManager.ins().removeListener(EventTag.GET_CURRENT_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PLAY, eventListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isFromPush) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack://返回
                finish();
                break;
            case R.id.rivImage:
                break;
        }
    }

}
